﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using SacNetUG.Helpers;
using SacNetUG.Models;
using System.Configuration;

namespace SacNetUG.Controllers
{
    public partial class TeamController : Controller
    {
        
        //TODO Sanitize user input for whole controller
        [Authorize]
        public virtual ActionResult Edit(int id)
        {
            var db = new SacNetUGDataContext();
            User user = db.GetTable<User>().Where(x => x.Id == id).FirstOrDefault();
            TeamUserViewModel tvm = new TeamUserViewModel();
            tvm.User = user;
            tvm.TeamMember = user.TeamMember;
            return View("Edit", tvm);
        }

        //public virtual ActionResult TestCreate(int? id)
        //{
        //    int selectedId = 16;
        //    var db = new SacNetUGDataContext();
        //    User user = db.GetTable<User>().Where(x => x.Id == selectedId).FirstOrDefault();
        //    TeamUserViewModel tvm = new TeamUserViewModel();
        //    tvm.User = user;
        //    tvm.TeamMember = new TeamMember();
        //    //wf.PersistData("selectedId", selectedId);

        //    //viewData.Model = tvm;
        //    return View("Create_EnterDetails", tvm);
        //}

        [ValidateInput(false)]
        [AcceptVerbs(HttpVerbs.Post), Authorize]
        public virtual ActionResult Edit(int id, TeamUserViewModel tvm)
        {
            //TODO: Replace this with updatemodel()
            var db = new SacNetUGDataContext();
            User user = db.GetTable<User>().Where(x => x.Id == id).FirstOrDefault();
            user.Bio = tvm.User.Bio;
            //user.TeamMember.ImageUrl = tvm.TeamMember.ImageUrl;
            user.TeamMember.Title = tvm.TeamMember.Title;
            user.TeamMember.IsCurrent = tvm.TeamMember.IsCurrent;
            //user.TeamMember.ImageUrl = tvm.TeamMember.ImageUrl;
            user.ImageUrl = tvm.User.ImageUrl;
            
            db.SubmitChanges();
            
            return RedirectToAction("Index");
        }
        
        [Authorize]
        public virtual ActionResult Edit_Image(int id)
        {
            TempData.Clear();
            TempData.Add("id", id);
            ViewData.Add("nextAction", "Edit_Image_Submit");
            return View("UploadFile");
        }

        [AcceptVerbs(HttpVerbs.Post), Authorize]
        public virtual ActionResult Edit_Image_Submit(FormCollection collection)
        {
            var db = new SacNetUGDataContext();
            int userId = int.Parse(TempData["id"].ToString());
            string uploadedFileName = GetFileName(Request.Files[0]);
            User user = db.Users.Where(x => x.Id == userId).FirstOrDefault();
            TeamMember teamMember = db.TeamMembers.Where(x => x.UserId == userId).FirstOrDefault();

            //teamMember.ImageFileName = string.IsNullOrEmpty(uploadedFileName) ? null : uploadedFileName;
            db.SubmitChanges();

            SaveFile(Request.Files[0], ConfigurationManager.AppSettings["TeamImageLocalDir"], user.Id);

            return RedirectToAction("Index");
        }

        public virtual ActionResult Index()
        {
            var db = new SacNetUGDataContext();

            string imageUrlRoot = ConfigurationManager.AppSettings["TeamImageWebDir"];
            ViewData.Add("imageUrlRoot", imageUrlRoot);
            TeamMemberViewModel tmvm = new TeamMemberViewModel();
            tmvm.CurrentMembers = db.GetTable<TeamMember>().Where(x => x.IsCurrent).OrderBy(x => x.Sequence);
            tmvm.PastMembers = db.GetTable<TeamMember>().Where(x => x.IsCurrent == false).OrderBy(x => x.Sequence);

            

            ViewData["RenderAdminLink"] = Models.User.UserInRole(HttpContext.User.Identity.Name, "Admin");

            return View(tmvm);
        }

        private string GetFileName(HttpPostedFileBase file)
        {
            return file.HasFile() ? Path.GetFileName(file.FileName) : "";
        }

        [Authorize]
        private void SaveFile(HttpPostedFileBase file, string dir, int userId)
        {
            string fileName = GetFileName(file);
            if (string.IsNullOrEmpty(fileName))
            {
                return;
            }
            string path = AppDomain.CurrentDomain.BaseDirectory + dir;
            file.SaveAs(Path.Combine(path, TeamMember.GetPersistedFileName(fileName, userId)));
        }

        [ValidateInput(false), Authorize]
        public virtual ActionResult Create(int? id, FormCollection collection)
        {

            WfManagerBase wf = new WfManagerBase(id, collection, ViewData, TempData, Request);
            wf.AddWfStep(new CreateSelectUser(wf));
            wf.AddWfStep(new CreateEnterDetails(wf));
            //wf.AddWfStep(new CreateUploadImage(wf));
            wf.AddWfStep(new CreateSubmit(wf));
            return wf.GetViewName(ReturnView, ReturnRedirectToAction);
            
        }

        [AcceptVerbs(HttpVerbs.Post), Authorize]
        public virtual ActionResult Delete(int id)
        {
            var db = new SacNetUGRepository();
            var tm = db.Db.Table<TeamMember>().Where(t => t.UserId == id).FirstOrDefault();
            db.Db.DeleteOnSubmit<TeamMember>(tm);
            db.Db.SubmitChanges();
            return RedirectToAction("Index");
        }

        [Authorize]
        public virtual ActionResult EditSequence()
        {
            var db = new SacNetUGDataContext();
            var team = from t in db.TeamMembers
                       select t.UserId;

            var teamUsers = from u in db.Users
                            where team.Contains(u.Id)
                            select u;
            return View(teamUsers);

        }

        [Authorize]
        private ActionResult ReturnView(string viewName)
        {
            return View(viewName);
        }


        [Authorize]
        private ActionResult ReturnRedirectToAction(string viewName)
        {
            return RedirectToAction(viewName);
        }

        //************************** WF step classes ************************************************

        private class CreateSelectUser : WfStepBase
        {

            public CreateSelectUser(WfManagerBase wf)
                : base(wf)
            {
            }

            public override string ActionNext(int? id, FormCollection collection, ViewDataDictionary viewData, TempDataDictionary tempData, HttpRequestBase request)
            {
                var db = new SacNetUGRepository();
                var users = db.Db.Table<User>().Where(x => x.TeamMember == null).OrderBy(x => x.LastName);

                SelectList sl = new SelectList(users, "Id", "Name");
                viewData.Add("userList", sl);

                return "Create_SelectUser";
            }

            public override string ActionBack(int? id, FormCollection collection, ViewDataDictionary viewData, TempDataDictionary tempData, HttpRequestBase request)
            {
                return ActionNext(id, collection, viewData, tempData, request);
            }

        }

        private class CreateEnterDetails : WfStepBase
        {

            public CreateEnterDetails(WfManagerBase wf) : base(wf)
            {
            }

            public override string ActionNext(int? id, FormCollection collection, ViewDataDictionary viewData, TempDataDictionary tempData, HttpRequestBase request)
            {
                int selectedId = int.Parse(collection["selectedUser"]);
                var db = new SacNetUGDataContext();
                User user = db.GetTable<User>().Where(x => x.Id == selectedId).FirstOrDefault();
                TeamUserViewModel tvm = new TeamUserViewModel();
                tvm.User = user;
                tvm.TeamMember = new TeamMember();
                wf.PersistData("selectedId", selectedId);

                viewData.Model = tvm;
                return "Create_EnterDetails";
            }

            public override string ActionBack(int? id, FormCollection collection, ViewDataDictionary viewData, TempDataDictionary tempData, HttpRequestBase request)
            {
                return "";
            }

        }

        private class CreateUploadImage : WfStepBase
        {
            public CreateUploadImage(WfManagerBase wf)
                : base(wf)
            {
            }

            public override string ActionNext(int? id, FormCollection collection, ViewDataDictionary viewData, TempDataDictionary tempData, HttpRequestBase request)
            {

                return "WfUploadFile";
            }

            public override string ActionBack(int? id, FormCollection collection, ViewDataDictionary viewData, TempDataDictionary tempData, HttpRequestBase request)
            {
                return "";
            }

        }

        private class CreateSubmit : WfStepBase
        {

            public CreateSubmit(WfManagerBase wf)
                : base(wf)
            {
            }

            public override string ActionNext(int? id, FormCollection collection, ViewDataDictionary viewData, TempDataDictionary tempData, HttpRequestBase request)
            {

                var db = new SacNetUGDataContext();
                int Id = (int)wf.GetPersistedData("selectedId");
                User user = db.Users.Where(x => x.Id == Id).FirstOrDefault();
                TeamMember tm = new TeamMember();

                

                //FormCollection prevCollection = (FormCollection)wf.GetPersistedData("CreateUploadImage.FormValues");

                //string uploadedFileName = GetFileName(request.Files[0]);

                //TODO: Replace this with updatemodel()
                user.Bio = collection["User.Bio"];
                //Checkbox returns string of 'true,false' for a true value. not sure why
                tm.IsCurrent = collection["TeamMember.IsCurrent"].StartsWith("true") ? true : false;
                //tm.ImageFileName = string.IsNullOrEmpty(uploadedFileName) ? null : uploadedFileName;
                tm.Title = collection["TeamMember.Title"];
                //tm.ImageUrl = collection["TeamMember.ImageUrl"];
                user.TeamMember = tm;
                user.ImageUrl = collection["User.ImageUrl"];
                db.SubmitChanges();

                //SaveFile(request.Files[0], ConfigurationManager.AppSettings["TeamImageLocalDir"], user.UserId);
                return "Index";
            }

            public override string ActionBack(int? id, FormCollection collection, ViewDataDictionary viewData, TempDataDictionary tempData, HttpRequestBase request)
            {
                return "";
            }

            private string GetFileName(HttpPostedFileBase file)
            {
                return file.HasFile() ? Path.GetFileName(file.FileName) : "";
            }

            private void SaveFile(HttpPostedFileBase file, string dir, int userId)
            {
                string fileName = GetFileName(file);
                if (string.IsNullOrEmpty(fileName))
                {
                    return;
                }
                string path = AppDomain.CurrentDomain.BaseDirectory + dir;
                file.SaveAs(Path.Combine(path, TeamMember.GetPersistedFileName(fileName, userId)));
            }
        }

    }


}
